'use strict'

import { app, protocol, BrowserWindow,Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
// 创建主窗口
async function createWindow() {
  const win = new BrowserWindow({
    // width: 800,
    // height: 600,
    minHeight:759,
    minWidth:1016,
    icon: `${__static}/app.png`,
    // eslint-disable-next-line no-undef
    webPreferences: {
      // webSecurity: false, // 允许跨域
      nodeIntegration: true // 是否完全支持node节点
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
    }
  })
  createMenu()
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    // win.loadURL('http://192.168.1.133:8086')
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
    // win.loadURL('http://192.168.1.133:8086')
  }
}
// 设置菜单栏
function createMenu() {
  // darwin表示macOS，针对macOS的设置
  if (process.platform === 'darwin') {
      const template = [
      {
          label: 'App Demo',
          submenu: [
              {
                  role: 'about'
              },
              {
                  role: 'quit'
              }]
      }]
      let menu = Menu.buildFromTemplate(template)
      Menu.setApplicationMenu(menu)
  } else {
      // windows及linux系统
      Menu.setApplicationMenu(null)
  }
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // Devtools extensions are broken in Electron  6/7/<8.25 on Windows
    // See https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/378 for more info
    // Electron will not launch with Devtools extensions installed on Windows 10 with dark mode
    // If you are not using Windows 10 dark mode, you may uncomment the following lines (and the import at the top of the file)
    // In addition, if you upgrade to Electron ^8.2.5 or ^9.0.0 then devtools should work fine

    // try {
    //   await installExtension(VUEJS_DEVTOOLS)
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }

  }
  createWindow()
})

if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
